
package com.rt.schedulenew.utils.aop;

import com.rt.schedulenew.utils.base.MillisecondClock;
import com.rt.schedulenew.utils.base.XmlUtil;
import org.slf4j.LoggerFactory;
import org.aspectj.lang.annotation.Around;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.Aspect;

@Aspect
@Component
public class WebServiceAspect {
    private Logger log = LoggerFactory.getLogger(WebServiceAspect.class);

    @Value("${authcode}")
    private String authcode;

    @Pointcut("execution(public * com.rt.*.ws.ScheduleServiceImpl.*(..))")
    private void webServiceAspect() {
    }

    @Around("webServiceAspect()")
    public Object methodAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTimeMillis = MillisecondClock.getInstance().now();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        log.info("【" + methodName + "】请求内容：{}", (args.length > 0 && StringUtils.isNotBlank(args[0].toString())) ? args[0].toString() : "null");
        Object result;
        try {
            if ("GetResponseByMethodName".equals(methodName)) {
                result = joinPoint.proceed();
            } else if (args.length > 0 && StringUtils.isNotBlank(args[0].toString())) {
                String req = args[0].toString().replace("<Header>", "").replace("</Header>", "");
                JSONObject xmlJsonObject = XmlUtil.xml2JSON(req);
                String reqAuthcode = xmlJsonObject.getString("authcode");
                if (StringUtils.isNotBlank(this.authcode) && !this.authcode.equals(reqAuthcode)) {
                    result = XmlUtil.object2xmlResponse("1", "服务验证码不正确");
                } else {
                    result = joinPoint.proceed();
                }
                result = joinPoint.proceed();
            } else {
                result = XmlUtil.object2xmlResponse("1", "获取请求内容为空，无法执行接口方法");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            log.error(e.getMessage());
            result = XmlUtil.object2xmlResponse("1", "系统出错");
        }
        log.info("【" + methodName + "】响应内容：{}", result);
        log.info("【" + methodName + "】响应耗时：{}毫秒", MillisecondClock.getInstance().now() - startTimeMillis);
        return result;
    }
}
